<template>
  <div class="courses-tree-list">
    <div class="search-box">
      <el-select
        v-model="searchForm.versionId"
        placeholder="请选择"
        @change="versionHandle"
      >
        <el-option
          v-for="item in versionOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>

      <!-- :remote-method="remoteMethod" -->
      <el-select
        v-model="searchForm.courseId"
        placeholder="请选择课程"
        @change="courseIdHandle"
      >
        <el-option
          v-for="item in courseOptions"
          :key="item.courseId"
          :label="item.courseName"
          :value="item.courseId"
        />
      </el-select>
    </div>
    <div class="tree-list-box">
      <el-tree
        :data="dataSource"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        :draggable="true"
        :allow-drag="allowDrag"
        :allow-drop="allowDrop"
        @node-drag-start="dragStartHandle"
        @node-drag-over="dragOverhHandle"
        @node-drag-end="dragEndHandle"
      >
        <template #default="{ node, data }">
          <div
            class="custom-tree-node"
            :class="
              !data.children || data.children.length === 0 ? 'last-lable' : ''
            "
          >
            <div class="lable">
              {{ data.catalogName }}
            </div>
            <div
              class="btn"
              v-if="!data.children || data.children.length === 0"
              @click="previewHandle(node)"
            >
              <!-- <img src="@/assets/classSchedule/see-icon.png" alt="" /> -->
              <span>预览</span>
            </div>
          </div>
        </template>
      </el-tree>
    </div>
  </div>
</template>

<script setup lang="ts">
import { type Form } from './FormBar.vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import type { TreeNodeData } from 'element-plus/es/components/tree/src/tree.type.mjs'

defineProps<{
  searchBarForm: Form | null
}>()

export type SearchLeftForm = {
  versionId: string
  versionName: string
  courseId: string
  courseName: string
}
type VersionOptions = {
  id: string
  name: string
}
type CourseOptions = {
  courseId: string
  courseName: string
  [prop: string]: unknown
}
export type Tree = {
  id: number
  catalogName: string
  parentId: number
  children: Tree[] | null
  resourceCount: ResourceCount
  [props: string]: unknown
}
interface ResourceCount {
  catalogId: number
  videoCount: number
  handoutCount: number
  testPaperCount: number
  practicePdfCount: number
  [props: string]: unknown
}
export type CoursesData = {
  id: number
  label: string
}

const searchForm = reactive<SearchLeftForm>({
  versionId: '',
  versionName: '',
  courseId: '',
  courseName: ''
})

const versionOptions = ref<VersionOptions[]>()

const courseOptions = ref<CourseOptions[]>([
  {
    courseId: '479',
    courseName: '20250820',
    phase: {
      phaseName: '小学',
      id: 1
    },
    subject: {
      id: 10,
      name: '科学'
    },
    standardGrade: {
      id: 53,
      name: '五年级'
    },
    edition: {
      id: 1,
      name: '通用版'
    },
    semester: {
      id: 1,
      name: '上学期'
    },
    resourceStatus: 1,
    courseType: {
      id: 2,
      typeName: '引桥课程',
      parentId: null,
      sortOrder: null,
      children: null
    },
    validityPeriod: '不限制'
  },
  {
    courseId: '98',
    courseName: '数学',
    phase: {
      phaseName: '初中',
      id: 2
    },
    subject: {
      id: 2,
      name: '数学'
    },
    standardGrade: {
      id: 59,
      name: '七年级'
    },
    edition: {
      id: 1,
      name: '通用版'
    },
    semester: {
      id: 1,
      name: '上学期'
    },
    resourceStatus: 1,
    courseType: {
      id: 2,
      typeName: '引桥课程',
      parentId: null,
      sortOrder: null,
      children: null
    },
    validityPeriod: '不限制'
  },
  {
    courseId: '97',
    courseName: '真实打印第二部',
    phase: {
      phaseName: '初中',
      id: 2
    },
    subject: {
      id: 9,
      name: '地理'
    },
    standardGrade: {
      id: 59,
      name: '七年级'
    },
    edition: {
      id: 1,
      name: '通用版'
    },
    semester: {
      id: 1,
      name: '上学期'
    },
    resourceStatus: 1,
    courseType: {
      id: 2,
      typeName: '引桥课程',
      parentId: null,
      sortOrder: null,
      children: null
    },
    validityPeriod: '不限制'
  },
  {
    courseId: '96',
    courseName: '真实打印',
    phase: {
      phaseName: '初中',
      id: 2
    },
    subject: {
      id: 9,
      name: '地理'
    },
    standardGrade: {
      id: 59,
      name: '七年级'
    },
    edition: {
      id: 1,
      name: '通用版'
    },
    semester: {
      id: 1,
      name: '上学期'
    },
    resourceStatus: 1,
    courseType: {
      id: 2,
      typeName: '引桥课程',
      parentId: null,
      sortOrder: null,
      children: null
    },
    validityPeriod: '不限制'
  }
])

const dataSource = ref<Tree[]>([])

const courseIdHandle = (val: string) => {
  const currentData = courseOptions.value.find(
    (item: CourseOptions) => item.courseId === val
  )
  searchForm.courseId = currentData?.courseId || ''
  searchForm.courseName = currentData?.courseName || ''
  Emit('searchLeftHandle', searchForm)
}
const versionHandle = (val: string) => {
  const currentData = versionOptions.value?.find(
    (item: VersionOptions) => item.id === val
  )
  searchForm.versionId = currentData?.id || ''
  searchForm.versionName = currentData?.name || ''
  Emit('searchLeftHandle', searchForm)
}

// Add these functions to the script
// 只有没有子节点的可以拖拽
const allowDrag = (draggingNode: { data: { children?: unknown[] } }) => {
  return !draggingNode.data.children || draggingNode.data.children.length === 0
}

// 控制拖拽放置位置
const allowDrop = () => {
  // type: 'prev' (之前), 'inner' (内部), 'next' (之后)
  //   console.log(type)
  return false
}

// 开始拖拽
const dragStartHandle = (node: Node, event: DragEvent) => {
  if (customDragImage.value) {
    // 储存被拖拽的数据
    moveData.value = node.data
    // 修改拖拽框样式
    customDragImage.value.innerHTML = `
    <div style="color: #fff">
        <div style="text-align:center;font-size:16px">正在布课</div>
        <div style="  margin-top: 10px;
          font-size: 14px;
          display: -webkit-box;
          overflow: hidden;
          text-overflow: ellipsis;
          word-wrap: break-word;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 3;
          line-clamp: 3;">${node.data.catalogName}</div>
    </div>`
    // setDragImage方法的三个参数，第一个是替换的dom，第二三个参数是拖动时鼠标在替换dom中的位置
    event.dataTransfer?.setDragImage(customDragImage.value, 125, 25)
  }
}
// 拖拽过程中修改鼠标样式，使其不出现禁止图标
const dragOverhHandle = (event: DragEvent) => {
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'move'
  }
}

const Emit = defineEmits<{
  (e: 'dragEndHandle', data: TreeNodeData): void
  (e: 'previewHandle', data: TreeNodeData): void
  (e: 'searchLeftHandle', data: SearchLeftForm): void
}>()

const dragEndHandle = (draggingNode: Node) => {
  Emit('dragEndHandle', draggingNode)
}

// 预览事件
const previewHandle = (node: Node) => {
  Emit('previewHandle', node)
}

// 获取版本
const getListEditionApi = () => {
  versionOptions.value = [
    {
      id: '1',
      name: '通用版'
    },
    {
      id: '2',
      name: '人教版'
    },
    {
      id: '3',
      name: '沪科版'
    },
    {
      id: '4',
      name: '统编版'
    },
    {
      id: '5',
      name: '外研版'
    },
    {
      id: '6',
      name: '沪粤版'
    },
    {
      id: '7',
      name: '苏教版'
    },
    {
      id: '8',
      name: '人教A版'
    },
    {
      id: '9',
      name: '人教B版'
    },
    {
      id: '10',
      name: '北师大版'
    }
  ]

  versionOptions.value?.unshift({
    id: '',
    name: '请选择'
  })
  if (versionOptions.value && versionOptions.value?.length !== 0) {
    searchForm.versionId = versionOptions.value[1].id
  }
}
getListEditionApi()

// 课程目录
const getCourseCatalogTreeApi = async () => {
  dataSource.value = [
    {
      id: 1024,
      catalogName: '培优-成语辨析',
      parentId: 0,
      leaf: 1,
      sortOrder: 0,
      courseId: 8,
      status: 1,
      children: null,
      completeSource: null,
      excellentCourseMapping: null,
      resourceCount: {
        catalogId: 1024,
        videoCount: 1,
        handoutCount: 1,
        testPaperCount: 0,
        testPdfCount: 1,
        testAnalysisPdfCount: 1,
        practicePaperCount: 0,
        practicePdfCount: 1,
        practiceAnalysisPdfCount: 1,
        totalCount: 6
      }
    },
    {
      id: 1026,
      catalogName: '培优-短语结构',
      parentId: 0,
      leaf: 1,
      sortOrder: 0,
      courseId: 8,
      status: 1,
      children: null,
      completeSource: null,
      excellentCourseMapping: null,
      resourceCount: {
        catalogId: 1026,
        videoCount: 0,
        handoutCount: 0,
        testPaperCount: 1,
        testPdfCount: 0,
        testAnalysisPdfCount: 0,
        practicePaperCount: 0,
        practicePdfCount: 0,
        practiceAnalysisPdfCount: 0,
        totalCount: 1
      }
    },
    {
      id: 2087,
      catalogName: '小程序',
      parentId: 0,
      leaf: 0,
      sortOrder: 0,
      courseId: 8,
      status: 1,
      children: [
        {
          id: 2088,
          catalogName: '1',
          parentId: 2087,
          leaf: 1,
          sortOrder: 0,
          courseId: 8,
          status: 1,
          children: null,
          completeSource: null,
          excellentCourseMapping: null,
          resourceCount: {
            catalogId: 2088,
            videoCount: 0,
            handoutCount: 0,
            testPaperCount: 0,
            testPdfCount: 0,
            testAnalysisPdfCount: 0,
            practicePaperCount: 1,
            practicePdfCount: 1,
            practiceAnalysisPdfCount: 1,
            totalCount: 3
          }
        },
        {
          id: 2310,
          catalogName: '11',
          parentId: 2087,
          leaf: 0,
          sortOrder: 0,
          courseId: 8,
          status: 1,
          children: null,
          completeSource: null,
          excellentCourseMapping: null,
          resourceCount: {
            catalogId: 2088,
            videoCount: 0,
            handoutCount: 0,
            testPaperCount: 0,
            testPdfCount: 0,
            testAnalysisPdfCount: 0,
            practicePaperCount: 1,
            practicePdfCount: 1,
            practiceAnalysisPdfCount: 1,
            totalCount: 3
          }
        }
      ],
      completeSource: null,
      excellentCourseMapping: null,
      resourceCount: {
        catalogId: 2087,
        videoCount: 0,
        handoutCount: 0,
        testPaperCount: 0,
        testPdfCount: 0,
        testAnalysisPdfCount: 0,
        practicePaperCount: 1,
        practicePdfCount: 1,
        practiceAnalysisPdfCount: 1,
        totalCount: 3
      }
    }
  ]
}

const customDragImage = ref<HTMLDivElement | null>(null)
const moveData = ref()
onMounted(() => {
  // 生成一个div，用户替换拖拽框
  const div = document.createElement('div')
  div.style.width = '168px'
  div.style.borderRadius = '4px'
  div.style.backgroundColor = '#b1c7f8'
  div.style.position = 'absolute'
  div.style.top = '-9999px'
  div.style.padding = '16px'
  document.body.appendChild(div)
  customDragImage.value = div

  // // 加载初始数据
  getCourseCatalogTreeApi()
})

watch(
  () => searchForm.courseId,
  () => {
    getCourseCatalogTreeApi()
  }
)

defineExpose({
  searchLeftFormData: () => searchForm
})
</script>

<style lang="scss" scoped>
.el-select {
  margin-bottom: 10px;
}
.tree-list-box {
  .btn {
    display: flex;
    align-items: center;
    img {
      display: block;
      width: 20px;
    }
    span {
      color: #165dff;
    }
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  &.last-lable {
    .lable {
      width: 136px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    &:hover {
      color: #165dff;
    }
  }
}
:deep(.el-tree-node__content) {
  &:hover {
    background-color: #e8f3ff;
  }
}
</style>
